<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <!-- 商品收藏 -->
  <div class="Mall4j con-box page-uc-collection">
    <!-- 导航 -->
    <div class="uc-nav">
      <div class="nav-box">
        <div
          :class="['nav-item', favType === 1 ? 'active' : '']"
          @click="favType = 1"
        >
          <span class="text">
            {{ $t('collection.productCollection') }}
            <em class="number">{{ prodFavNum > 0 ? prodFavNum : null }}</em>
          </span>
          <i class="line" />
        </div>
        <div
          :class="['nav-item', favType === 2 ? 'active' : '']"
          @click="favType = 2"
        >
          <span class="text">
            {{ $t('collection.storeCollection') }}
            <em class="number">{{ shopFavNum > 0 ? shopFavNum : null }}</em>
          </span>
          <i class="line" />
        </div>
      </div>
    </div>
    <!-- /导航 -->
    <!-- 搜索 -->
    <div class="uc-serach">
      <div class="left">
        <div
          v-if="favType === 1"
          class="select-item"
        >
          <span
            class="tit"
            @click="prodTypeSearch===2?2:0"
          >{{
            prodTypeSearch === 0 ? $t('collection.allProducts') : $t('collection.failedProducts')
          }}</span>
          <div class="select">
            <span
              class="s-item"
              @click="prodTypeSearch = 0"
            >{{ $t('collection.allProducts') }}</span>
            <span
              class="s-item"
              @click="prodTypeSearch = 2"
            >{{ $t('collection.failedProducts') }}</span>
          </div>
        </div>
        <div class="action-btn">
          <a
            href="javascript:void(0);"
            class="batch"
            @click="batchManager($event)"
          >{{ $t('collection.batchManagement') }}</a>
        </div>
        <div class="action-btn active">
          <a
            v-if="isBatchEdit"
            href="javascript:void(0);"
            class="batch"
            @click="overManager()"
          >{{ $t('collection.completeManagement') }}</a>
          <span
            v-if="isBatchEdit"
            class="batch-box"
          >
            <span
              class="check"
              @click="checkAll()"
            >
              <input
                type="checkbox"
                class="checkbox default"
                :class="{ checked: checkAllData, default: !checkAllData }"
              >
              <span class="text">{{ $t('collection.selectAll') }}</span>
            </span>
            <span
              class="cancel-collection"
              @click="showPopup()"
            >
              <i class="icon" />
              <span class="text">{{ $t('collection.cancelCollection') }}</span>
            </span>
          </span>
        </div>
      </div>
      <div class="right">
        <input
          v-model="prodNameSearch"
          type="text"
          class="input"
          :placeholder="favType === 1 ? $t('collection.enterProductName') : $t('collection.enterStoreuctName')"
          @keyup.enter="searchFavProdList(true)"
        >
        <a
          href="javascript:void(0)"
          class="search"
          @click="searchFavProdList(true)"
        >{{ $t('collection.Search') }}</a>
      </div>
    </div>
    <!-- /搜索 -->
    <!-- 收藏列表 -->
    <div class="goods-list">
      <div class="list-con">
        <div
          v-for="(data, index) in favType === 1 ? prodFavList : shopFavList"
          :key="index"
          :class="[
            'item',
            isBatchEdit ? 'batch-edit' : '',
            data.isCheck ? 'checked' : ''
          ]"
          @click="selectIt(index); addProdCartOrIntoShop(data)"
        >
          <div class="goods-img">
            <div v-if="favType === 1">
              <img
                v-if="data.pic"
                :src="checkFileUrl(data.pic)"
                alt
                @error="handlePicError"
              >
              <img
                v-else
                src="@/assets/img/def.png"
                alt
              >
            </div>
            <div v-else>
              <img-show :src="data.shopLogo" />
            </div>
          </div>
          <div class="goods-msg">
            <div class="goods-name">
              {{ favType === 1 ? data.prodName : data.shopName }}
            </div>
            <div class="goods-price">
              <div
                v-if="favType === 1"
                class="price"
              >
                ￥
                <span class="big">{{ parsePrice(data.price)[0] }}.{{
                  parsePrice(data.price)[1]
                }}</span>
              </div>
            </div>
          </div>
          <div class="goods-action">
            <a
              href="javascript:void(0)"
              class="action-a a1"
            >
              <i class="icon" />
              {{ favType === 1 ? $t('collection.goToBuy') : $t('collection.enterStore') }}
            </a>
            <a
              href="javascript:void(0)"
              class="action-a a2"
              @click.stop="showPopup(favType === 1 ? data.prodId : data.shopId)"
            >
              <i class="icon" />{{ $t('collection.cancelCollection') }}
            </a>
          </div>
          <div class="item-mask">
            <i class="icon" />
          </div>
        </div>
        <!-- 收藏的店铺或者商品 -->
      </div>
      <!-- 页码 -->
      <pagination
        v-model="current"
        :pages="pages"
        @change-page="getSearchProdPage"
      />
      <!-- /页码 -->
    </div>
    <!-- /收藏列表 -->
    <!-- 空列表提示 -->
    <empty-all-tips
      v-if="isEmpty && favType === 1"
      :text="$t('collection.noCollection')"
      :back="$t('collection.lookOther')"
      :src-type="2"
    />
    <empty-all-tips
      v-if="isEmptyTwo && favType === 2"
      :text="$t('collection.noCollection')"
      :back="$t('collection.lookOther')"
      :src-type="2"
    />
    <!-- /空列表提示 -->
    <!-- 提示弹窗 -->
    <div
      v-if="visible"
      class="popup-mask"
    />
    <div
      v-if="visible"
      class="popup-box"
    >
      <div class="tit">
        <div class="text">
          {{ $t('tips') }}
        </div>
        <div
          class="close"
          @click="closePopup()"
        />
      </div>
      <div class="con">
        <div class="tip">
          <div class="tip-icon warning" />
          <div class="tip-info">
            <div class="result">
              {{ $t('collection.unbookmark1') }}{{ favType === 1 ? $t('collection.product') : $t('collection.store') }}？
            </div>
            <div class="date">
              {{ $t('collection.unbookmark2') }}{{ favType === 1 ? $t('collection.product') : $t('collection.store') }}{{ $t('collection.unbookmark3') }}
            </div>
            <div class="btns">
              <a
                href="JavaScript:"
                class="btn-r"
                @click="confirmCancel()"
              >{{ $t('determine') }}</a>
              <a
                href="JavaScript:"
                class="btn-g"
                @click="closePopup()"
              >{{ $t('cancel') }}</a>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- /提示弹窗 -->
  </div>
  <!-- /商品收藏 -->
</template>

<script setup>
import defPng from '@/assets/img/def.png'
import { ElMessage } from 'element-plus'
import { checkFileUrl } from '@/utils/index.js'
const router = useRouter()

// 1 商品收藏 2 店铺收藏
const favType = ref(1)
const current = ref(1) // 当前页
watch(() => favType.value, () => {
  current.value = 1
  getFavList()
})

const prodTypeSearch = ref(0) // 0 全部商品 1 降价商品 2 失效商品
watch(() => prodTypeSearch.value, () => {
  search()
})

onMounted(() => {
  // 设置网页标题
  document.title = $t('collection.myCollection')
  getFavProdNum()
  getFavShopNum()
  getFavList()
})

const init = (favTypePar) => {
  favType.value = favTypePar
  getFavList()
}

/**
 * 加载默认图片
 */
const handlePicError = (e) => {
  e.target.src = defPng
}

/**
 * 获取收藏列表
 */
const getFavList = () => {
  overManager()
  if (favType.value === 1) {
    getFavProdList()
  } else if (favType.value === 2) {
    getFavShopList()
  }
}

const isEmpty = ref(false)
const size = 12
// 商品收藏列表
const prodFavList = ref([])
const pages = ref(1) // 总页数
/**
 * 获取商品收藏列表
 */
const getFavProdList = () => {
  isEmpty.value = false
  const params = {
    prodType: prodTypeSearch.value,
    current: current.value,
    size
  }
  http.get('/p/user/collection/page', { params }).then(({ data }) => {
    prodFavList.value = data.records
    isEmpty.value = !prodFavList.value.length
    pages.value = data.pages
    current.value = data.current
    // 给每一个列表初始化一个未选中状态
    for (let index = 0; index < data.records.length; index++) {
      prodFavList.value[index].isCheck = false
    }
  })
}

const getSearchProdPage = () => {
  if (favType.value === 1) {
    favType.value = 1
    search()
  } else if (favType.value === 2) {
    favType.value = 2
    search()
  }
}

const isEmptyTwo = ref(false)
// 店铺收藏类别
const shopFavList = ref([])
/**
 * 获取店铺收藏列表
 */
const getFavShopList = () => {
  isEmptyTwo.value = false
  const params = {
    current: current.value,
    renovationType: 1,
    size
  }
  http.get('/p/shop/collection/page', { params }).then(({ data }) => {
    shopFavList.value = data.records
    isEmptyTwo.value = !shopFavList.value.length
    pages.value = data.pages
    current.value = data.current
    // 给每一个列表初始化一个未选中状态
    for (let index = 0; index < data.records.length; index++) {
      shopFavList.value[index].isCheck = false
    }
  })
}

const prodFavNum = ref(null)
/**
 * 获取商品收藏的数量
 */
const getFavProdNum = () => {
  http.get('/p/user/collection/count').then(({ data }) => {
    prodFavNum.value = data
  })
}

const shopFavNum = ref(null)
/**
 * 获取店铺收藏的数量
 */
const getFavShopNum = () => {
  http.get('/p/shop/collection/count').then(({ data }) => {
    shopFavNum.value = data
  })
}

const searchFavProdList = (newData = false) => {
  current.value = 1
  search(newData)
}

let theData = null // 保存上次点击查询的请求条件
const prodNameSearch = ref(null)
/**
 * 搜索
 */
const search = (newData = false) => {
  if (favType.value === 1) {
    if (newData || !theData) {
      theData = {
        prodName: prodNameSearch.value,
        prodType: prodTypeSearch.value,
        current: current.value,
        size
      }
    } else {
      theData.current = current.value
      theData.size = size
      theData.prodType = prodTypeSearch.value
    }
    http.get('/p/user/collection/page', { params: theData }).then(({ data }) => {
      prodFavList.value = data.records
      isEmpty.value = !prodFavList.value.length
      current.value = data.current
      pages.value = data.pages
      // 给每一个列表初始化一个未选中状态
      for (let index = 0; index < data.records.length; index++) {
        prodFavList.value[index].isCheck = false
      }
    })
  } else if (favType.value === 2) {
    const params = {
      shopName: prodNameSearch.value,
      renovationType: 1,
      current: current.value,
      size
    }
    http.get('/p/shop/collection/page', { params }).then(({ data }) => {
      shopFavList.value = data.records
      isEmptyTwo.value = !shopFavList.value.length
      current.value = data.current
      pages.value = data.pages
      // 给每一个列表初始化一个未选中状态
      for (let index = 0; index < data.records.length; index++) {
        shopFavList.value[index].isCheck = false
      }
    })
  }
}

// 开启批量管理
const isBatchEdit = ref(false)
/**
 * 去购买或者进入店铺
 */
const addProdCartOrIntoShop = (data) => {
  if (isBatchEdit.value) {
    return
  }
  if (favType.value === 1) {
    // 去购买
    toProdDetail(data)
  } else if (favType.value === 2) {
    // 进入店铺
    toShopDetail(data)
  }
}
/**
* 跳转到商品详情页
*/
const toProdDetail = (data) => {
  // status -1:删除、0:商家下架、1:上架、2:违规下架、3:平台审核
  if (data.status === 1) {
    const newPage = router.resolve({ path: '/detail', query: { prodId: data.prodId } })
    window.open(newPage.href, '_blank', 'noopener,noreferrer')
  } else {
    ElMessage({
      message: $t('collection.notPurchase'),
      type: 'warning',
      duration: 1500
    })
  }
}

/**
* 跳转到店铺页
*/
const toShopDetail = (data) => {
  // 未开通/已删除
  if (data.shopStatus === -1) {
    ElMessage({
      type: 'warning',
      message: $t('collection.storeReviewTips2'),
      duration: 1000
    })
    return
  }
  // 已下线
  if (data.shopStatus === 2 || data.shopStatus === 3) {
    ElMessage({
      type: 'warning',
      message: $t('collection.storeReviewTips3'),
      duration: 1000
    })
    return
  }
  // 停业中
  if (data.shopStatus === 0) {
    const contractStartTime = new Date(data.contractStartTime).getTime()
    const contractEndTime = new Date(data.contractEndTime).getTime()
    const today = new Date().getTime()
    // 1、店铺状态为0(停业中)时，当店铺未到签约开始时间，用户进入店铺提示：商家尚未营业
    if (today < contractStartTime) {
      ElMessage({
        type: 'warning',
        message: '商家尚未营业',
        duration: 1000
      })
      return
    }
    // 2、店铺状态为0(停业中)时，当店铺超过签约有效期，用户进入店铺提示：商家已暂停未营业
    if (today > contractEndTime) {
      ElMessage({
        type: 'warning',
        message: '商家已暂停营业',
        duration: 1000
      })
      return
    }
  }
  router.push({
    path: '/shop-index',
    query: {
      sid: data.shopId
    }
  })
}

let id = 0 // 商品id或店铺id
/**
 * 取消收藏
 */
const cancelFav = () => {
  // 取消商品收藏
  if (favType.value === 1) {
    http.post('/p/user/collection/addOrCancel', id).then(() => {
      current.value = 1
      getFavProdList()
      getFavProdNum()
      overManager()
    })
  } else if (favType.value === 2) {
    // 取消店铺收藏
    http.post('/p/shop/collection/addOrCancel', id).then(() => {
      current.value = 1
      getFavShopList()
      getFavShopNum()
      overManager()
    })
  }
}

let prodIds = [] // 取消收藏选择商品列表
let shopIds = [] // 取消收藏选择店铺列表
/**
 * 批量取消收藏
 */
const batachCancel = () => {
  if (favType.value === 1) {
    // 商品批量取消收藏
    http.post('/p/user/collection/batachCancel', prodIds).then(() => {
      current.value = 1
      getFavProdList()
      getFavProdNum()
      overManager()
    })
  } else if (favType.value === 2) {
    // 店铺批量取消收藏
    http.post('/p/shop/collection/batachCancel', shopIds).then(() => {
      current.value = 1
      getFavShopList()
      getFavShopNum()
      overManager()
    })
  }
}

let type = null
const visible = ref(false) // 提示弹窗
/**
 * 确认取消收藏
 */
const confirmCancel = () => {
  if (type === 1) {
    cancelFav() // 取消收藏
  } else if (type === 2) {
    batachCancel() // 批量取消收藏
  }
  visible.value = false
}
/**
* 提示弹窗显示
*/
const showPopup = (idPar) => {
  if (idPar) {
    id = idPar
    type = 1
    visible.value = true
  } else {
    type = 2
    if (favType.value === 1) {
      // 获取到批量提交的数据
      const prodIdsPar = []
      for (let index = 0; index < prodFavList.value.length; index++) {
        if (prodFavList.value[index].isCheck) {
          prodIdsPar.push(prodFavList.value[index].prodId)
        }
      }
      prodIds = prodIdsPar
      if (prodIds.length < 1) {
        overManager()
      } else {
        visible.value = true
      }
    } else if (favType.value === 2) {
      const shopIdsPar = []
      for (let index = 0; index < shopFavList.value.length; index++) {
        if (shopFavList.value[index].isCheck) {
          shopIdsPar.push(shopFavList.value[index].shopId)
        }
      }
      shopIds = shopIdsPar
      if (shopIds.length < 1) {
        overManager()
      } else {
        visible.value = true
      }
    }
  }
}

/**
 * 提示弹窗隐藏
 */
const closePopup = () => {
  visible.value = false
}

/**
 * 点击开启 批量管理
 */
const batchManager = () => {
  isBatchEdit.value = true
}

const checkAllData = ref(false)
/**
 * 完成批量管理
 */
const overManager = () => {
  isBatchEdit.value = false
  checkAllData.value = false
  if (favType.value === 1) {
    for (let index = 0; index < prodFavList.value.length; index++) {
      prodFavList.value[index].isCheck = false
    }
  } else if (favType.value === 2) {
    for (let index = 0; index < shopFavList.value.length; index++) {
      shopFavList.value[index].isCheck = false
    }
  }
}

/**
 * 点击选中
 */
const selectIt = (index) => {
  if (!isBatchEdit.value) {
    return
  }
  if (favType.value === 1) {
    prodFavList.value[index].isCheck = !prodFavList.value[index].isCheck
  } else if (favType.value === 2) {
    shopFavList.value[index].isCheck = !shopFavList.value[index].isCheck
  }
  checkAllSelect() // 检查全选
}

/**
 *  全选事件
 */
const checkAll = () => {
  checkAllData.value = !checkAllData.value
  // 全选商品
  if (favType.value === 1) {
    selectAll(prodFavList.value, !checkAllData.value)
  } else if (favType.value === 2) {
    selectAll(shopFavList.value, !checkAllData.value)
  }
}

/**
 * 检查全选
 */
const checkAllSelect = () => {
  checkAllData.value = true
  if (favType.value === 1) {
    for (let i = 0; i < prodFavList.value.length; i++) {
      if (!prodFavList.value[i].isCheck) {
        checkAllData.value = false
        break
      }
    }
    return
  }
  if (favType.value === 2) {
    for (let i = 0; i < shopFavList.value.length; i++) {
      if (!shopFavList.value[i].isCheck) {
        checkAllData.value = false
        break
      }
    }
  }
}

/**
 * 价格过滤
 */
const parsePrice = (value) => {
  let val = Number(value)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

/**
 * 勾选/取消全选商品
 */
const selectAll = (data, isChecked) => {
  if (isChecked) {
    for (let index = 0; index < data.length; index++) {
      data[index].isCheck = false
    }
  } else {
    for (let index = 0; index < data.length; index++) {
      data[index].isCheck = true
    }
  }
  if (favType.value === 1) {
    prodFavList.value = data
  } else if (favType.value === 2) {
    shopFavList.value = data
  }
}

defineExpose({
  init
})

</script>

<style lang="scss" scoped>
@use "index";
</style>

<style lang="scss" scoped>
@use "../common/scss/user-center";
</style>
